package com.example.zhyq.sign

import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.SignBeanItem
import com.example.base.mvvm.BaseActivity
import com.example.zhyq.databinding.ActivitySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask


@AndroidEntryPoint
@Route(path = "/app/SignActivity")
class SignActivity : BaseActivity<ActivitySignBinding,SignViewModel>() {

    var mapView:MapView?=null
    var baiduMap:BaiduMap?=null
    val mLocationClient:LocationClient?=null

    var timer:Timer?=null

    override fun initView() {
        initMap()
        val spUtils = SPUtils.getInstance()

        val signTime = spUtils.getString("sign")//取出签到的日期时间
        val today = vm.getData(System.currentTimeMillis())//今天日期
        if (signTime.isNotEmpty()) { //说明打过签到卡
            if (signTime.split(" ")[0] == today) {//说明今天打过签到
                val time = signTime.split(" ")[1]
                binding.signStartTime.text = time
                if (time>"09:00:00") {
                    binding.signStartTime.append("(迟到)")
                }
                binding.tvSignText.setText("签退")
            }

            val soutTime = spUtils.getString("sout")//取出签退的日期时间
            if (soutTime.isNotEmpty()) {
                if (soutTime.split(" ")[0]==today) {
                    val time = soutTime.split(" ")[1]
                    binding.signEndTime.text = time
                    if (time<"18:00:00") {
                        binding.signEndTime.append("早退")
                    }
                    binding.btnSign.isEnabled=false
                }
            }
        }

        lifecycleScope.launch {
            timer= Timer()
            timer?.schedule(timerTask {
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.tvTime.setText(vm.getTime(System.currentTimeMillis()))
                }
            },0,1000)
        }

        binding.btnSign.apply {
            setOnClickListener {
                var item:SignBeanItem?=null
                var status = "正常"
                val dataTime = vm.getDataTime(System.currentTimeMillis())
                val time = dataTime.split(" ")[1]
                if (binding.tvSignText.text.toString()=="签到") {
                    binding.signStartTime.text = time
                    if (time>"09:00:00") {
                        status="迟到"
                        binding.signStartTime.append("($status)")
                    }
                    item = SignBeanItem(
                        "", "天津", null, "天津",
                        dataTime, status, SPUtils.getInstance().getInt("uid"), null
                    )
                    binding.tvSignText.setText("签退")
                    spUtils.put("sign",dataTime)
                }else {
                    binding.signEndTime.text = time
                    if (time<"18:00:00") {
                        status="早退"
                        binding.signEndTime.append("$status")
                    }
                    item = SignBeanItem(
                        dataTime, "天津", null, "天津",
                        "", status, SPUtils.getInstance().getInt("uid"), null
                    )
                    isEnabled=false
                    spUtils.put("sout",dataTime)
                }
                vm.sign(item)
            }
        }

        binding.headerSign.apply {
            headerBack.setOnClickListener {
                finish()
            }
            headerTitle.text = "考勤打卡"
            headerAdd.visibility = View.GONE
        }
    }

    fun initMap() {
        mapView=binding.mapView
        baiduMap= mapView!!.map
        baiduMap!!.isMyLocationEnabled=true
        LocationClient.setAgreePrivacy(true)
        //定位初始化
        //定位初始化
        val mLocationClient = LocationClient(this)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps

        option.setCoorType("bd09ll") // 设置坐标类型

        option.setScanSpan(1000)

//设置locationClientOption

//设置locationClientOption
        mLocationClient.setLocOption(option)

//注册LocationListener监听器

//注册LocationListener监听器
        val myLocationListener = MyLocationListener()
        mLocationClient.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
        mLocationClient.start()
    }
    override fun initData() {
        vm.sign.observe(this) {
            ToastUtils.showLong("打卡成功")
        }
    }

    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return
            }
            val locData = MyLocationData.Builder()
                .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.direction).latitude(location.latitude)
                .longitude(location.longitude).build()

            //定位蓝点额外加的
            val ll = LatLng(location.latitude, location.longitude)
            val update = MapStatusUpdateFactory.newLatLngZoom(ll, 5f)
            baiduMap!!.animateMapStatus(update)

            baiduMap!!.setMyLocationData(locData)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.stop();
        baiduMap?.setMyLocationEnabled(false);
        mapView?.onDestroy();
        mapView = null;

        if (timer!=null) {
            timer?.cancel()
            timer==null
        }
    }
}